#include <sys/types.h>
#include <sys/socket.h>
#include <string.h>
#include <stdio.h>
#include <errno.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <stdlib.h>
#define MSG_STR "AAAAaaaaa"
int main(int argc, char **argv)
{

        int             	socket_fd = -1;
	int 			rv = -1;
	struct sockaddr_in	servaddr;
	char 			*servip = "192.168.2.40";
	int 			port = 12345;
	char 			read_buf[1024];

	if(argc < 3)
	{

		printf("program  usage: %s [serverIP] [Port] \n",argv[0]);
		return -1;
	}

	servip = argv[1];
	port = atoi(argv[2]);

        socket_fd = socket(AF_INET, SOCK_STREAM, 0);
        if(socket_fd < 0)
        {
                printf("Create socket failure: %s \n",strerror(errno));
                return -1;
        }
        printf("connect socket {%d} successfully!\n ",socket_fd);
	
	memset(&servaddr,0,sizeof(servaddr)); 
	servaddr.sin_family = AF_INET;
	servaddr.sin_port = htons(port);
	inet_aton(servip,&servaddr.sin_addr);

        rv =  connect(socket_fd, (struct sockaddr *)&servaddr, sizeof(servaddr)); 
       if (rv < 0)
       {
		printf("connet to server [%s,%d] failure :%s\n",servip,port,strerror(errno));
		return -2;
		
       }	       
       printf("connet to server [%s,%d] successfully\n ",servip,port );

      rv =  write(socket_fd,MSG_STR,strlen(MSG_STR));
      if(rv < 0 )
      {
		printf("write to server by socket[%d] failure:%s \n",socket_fd,strerror(errno));
		return -3;
      }
      while(1)
      {	
	     	memset(read_buf,0,sizeof(read_buf));
     	      	rv = read(socket_fd,read_buf,sizeof(read_buf));
      		if(rv < 0)
     		 {
 			printf("read data from server by socket[%d] failure:%s\n",
				socket_fd,strerror(errno));
			return -4;
     		 }	

     		 else if (rv == 0)
      		{

			printf("socket[%d] get disconneted\n",socket_fd);
			return -5;
		
      		}
      		else if(rv > 0)
      		{
			printf("Read %d bytes data form server: %s \n",rv,read_buf);

      		}	

      }
      close(socket_fd);
      return 0;
}



